package threading;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-03-28
 * Time: 20:35
 */
public class ThreadExample_unsafe2 {
    //解决方法：加关键字volatile取消对该变量的编译器优化
    //public static int flag = 0;
    volatile public static int flag = 0;
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            while (flag == 0) {
                //空转
            }
            System.out.println("循环结束，t1结束！");
        });

        Thread t2 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
//            System.out.print("请输入一个整数:");
//            flag = scanner.nextInt();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag= 1;
        });

        t1.start();
        t2.start();
    }
}
